package com.niannian.photo;

import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.niannian.activity.PushRegardsActivity;
import com.niannian.photo.AlbumGridViewAdapter;
import com.niannian.photo.FolderAdapter;
import com.niannian.photo.AlbumHelper;
import com.niannian.photo.Bimp;
import com.niannian.photo.ImageBucket;
import com.niannian.photo.ImageItem;
import com.niannian.photo.PublicWay;
import com.niannian.util.VAR;

/**
 * 这个是进入相册显示所有图片的界面
 * 
 */
public class AlbumActivity extends BaseActivity {
	// 显示手机里的所有图片的列表控件
	private GridView gridView;
	// 当手机里没有图片时，提示用户没有图片的控件
	private TextView tv;
	// gridView的adapter
	private AlbumGridViewAdapter gridImageAdapter;
	// 完成按钮
	private Button okButton;
	// 返回按钮
	private Button back;
	// 取消按钮
	private ImageView cancel;
	private Intent intent;
	// 预览按钮
	private Button preview;
	private Context mContext;
	private ArrayList<ImageItem> dataList;
	private AlbumHelper helper;
	public static List<ImageBucket> contentList;
	public static Bitmap bitmap;
	PopupWindow pop;

	public static String photoPath = "";

	int sendType = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addActToGroup("photo", this);
		setContentView(R.layout.p_plugin_camera_album);

		sendType = getIntent().getIntExtra("from", 0);
		mContext = this;
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.plugin_camera_no_pictures);
		init();
		initListener();
		// 这个函数主要用来控制预览和完成按钮的状态
		isShowOkBt();
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// mContext.unregisterReceiver(this);
			// TODO Auto-generated method stub
			gridImageAdapter.notifyDataSetChanged();
		}
	};

	// 预览按钮的监听
	private class PreviewListener implements OnClickListener {
		public void onClick(View v) {
			if (Bimp.tempSelectBitmap.size() > 0) {
				intent.putExtra("position", "1");
				intent.putExtra("from", sendType);
				intent.setClass(AlbumActivity.this, GalleryActivity.class);
				startActivity(intent);
			}
		}

	}

	// 完成按钮的监听
	private class AlbumSendListener implements OnClickListener {
		public void onClick(View v) {

			if (sendType == PushRegardsActivity.FROM_MIAN_PIC) {
				startActivity(new Intent(AlbumActivity.this, PushRegardsActivity.class).putExtra("from", PushRegardsActivity.FROM_MIAN_PIC));
			}
			myfinish();
			destroyGroup("photo");
		}

	}

	// 返回按钮监听
	private class BackListener implements OnClickListener {
		public void onClick(View v) {
			// intent.setClass(AlbumActivity.this, ImageFile.class);
			// startActivity(intent);

			pop.showAtLocation(back, Gravity.TOP, 0, 0);
			// pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);

		}
	}

	// 取消按钮的监听
	private class CancelListener implements OnClickListener {
		public void onClick(View v) {
			// Bimp.tempSelectBitmap.clear();1
			// intent.setClass(mContext, PushRegardsActivity.class);
			// startActivity(intent);
			if (sendType == PushRegardsActivity.FROM_MIAN_PIC && Bimp.tempSelectBitmap.size() > 0) {
				startActivity(new Intent(AlbumActivity.this, PushRegardsActivity.class).putExtra("from", PushRegardsActivity.FROM_MIAN_PIC));
			}

			myfinish();
			destroyGroup("photo");
		}
	}

	// 初始化，给一些对象赋值
	private void init() {
		helper = new AlbumHelper();
		helper.init(getApplicationContext());

		contentList = helper.getImagesBucketList(true);
		dataList = new ArrayList<ImageItem>();
		ImageItem imageItem = new ImageItem();
		dataList.add(imageItem);
		int tunm = 0;
		for (int i = 0; i < contentList.size(); i++) {
			dataList.addAll(contentList.get(i).imageList);
			tunm = tunm + contentList.get(i).imageList.size();
		}

		ImageBucket bucket = new ImageBucket();

		bucket.imageList = dataList;
		bucket.bucketName = "所有照片";
		bucket.count = tunm;
		contentList.add(0, bucket);
		back = (Button) findViewById(R.id.back);
		cancel = (ImageView) findViewById(R.id.cancel);
		cancel.setOnClickListener(new CancelListener());
		back.setOnClickListener(new BackListener());
		back.setText("所有照片");
		preview = (Button) findViewById(R.id.preview);
		preview.setOnClickListener(new PreviewListener());
		intent = getIntent();

		gridView = (GridView) findViewById(R.id.myGrid);
		gridImageAdapter = new AlbumGridViewAdapter(this, dataList, Bimp.tempSelectBitmap);
		gridView.setAdapter(gridImageAdapter);
		tv = (TextView) findViewById(R.id.myText);
		gridView.setEmptyView(tv);
		okButton = (Button) findViewById(R.id.ok_button);
		okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");

		pop = new PopupWindow(AlbumActivity.this);

		View view = getLayoutInflater().inflate(R.layout.p_album_popuwindows, null);

		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);

		ListView list_album = (ListView) view.findViewById(R.id.list_album);

		FolderAdapter folderAdapter = new FolderAdapter(this);
		list_album.setAdapter(folderAdapter);

		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
			}
		});

		list_album.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				gridImageAdapter.setData(contentList.get(arg2).imageList, arg2);
				gridImageAdapter.notifyDataSetChanged();
				pop.dismiss();
				back.setText(contentList.get(arg2).bucketName);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case VAR.TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9) {

				// String fileName = String.valueOf(System.currentTimeMillis());
				// Bitmap bm = (Bitmap) data.getExtras().get("data");
				// // FileUtils.saveBitmap(bm, fileName);
				//
				// String pic = MyApplication.FILE_PATH_TEMP + "nn" + ((new
				// Date()).getTime() / 1000) + "pictemp.jpg";
				// File file = new File(pic);
				// if (file.exists()) {
				// file.delete();
				// }
				// BitmapUtil.saveBmp(bm, pic, 100);

				ImageItem takePhoto = new ImageItem();
				takePhoto.setImagePath(photoPath);
				// takePhoto.setBitmap(bm);
				Bimp.tempSelectBitmap.add(takePhoto);

				if (sendType == PushRegardsActivity.FROM_MIAN_PIC && Bimp.tempSelectBitmap.size() > 0) {
					startActivity(new Intent(AlbumActivity.this, PushRegardsActivity.class).putExtra("from", PushRegardsActivity.FROM_MIAN_PIC));
				}
				myfinish();
				destroyGroup("photo");
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (sendType == PushRegardsActivity.FROM_MIAN_PIC && Bimp.tempSelectBitmap.size() > 0) {
			startActivity(new Intent(AlbumActivity.this, PushRegardsActivity.class).putExtra("from", PushRegardsActivity.FROM_MIAN_PIC));
		}
		myfinish();
		destroyGroup("photo");
	}

	private void initListener() {
		gridImageAdapter.setOnItemClickListener(new AlbumGridViewAdapter.OnItemClickListener() {

			@Override
			public void onItemClick(final ToggleButton toggleButton, int position, boolean isChecked, Button chooseBt) {
				if (Bimp.tempSelectBitmap.size() >= PublicWay.num) {
					toggleButton.setChecked(false);
					chooseBt.setVisibility(View.GONE);
					if (!removeOneData(gridImageAdapter.getdata().get(position))) {
						Toast.makeText(AlbumActivity.this, "你最多只能选择" + PublicWay.num + "张照片", 200).show();
					}
					return;
				}
				if (isChecked) {
					chooseBt.setVisibility(View.VISIBLE);
					Bimp.tempSelectBitmap.add(gridImageAdapter.getdata().get(position));
					okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
				} else {
					Bimp.tempSelectBitmap.remove(gridImageAdapter.getdata().get(position));
					chooseBt.setVisibility(View.GONE);
					okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
				}
				isShowOkBt();
			}
		});

		okButton.setOnClickListener(new AlbumSendListener());

	}

	private boolean removeOneData(ImageItem imageItem) {
		if (Bimp.tempSelectBitmap.contains(imageItem)) {
			Bimp.tempSelectBitmap.remove(imageItem);
			okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
			return true;
		}
		return false;
	}

	public void isShowOkBt() {
		if (Bimp.tempSelectBitmap.size() > 0) {
			okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
			preview.setEnabled(true);
			okButton.setEnabled(true);
			preview.setEnabled(true);
			okButton.setEnabled(true);

		} else {
			okButton.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" + PublicWay.num + ")");
			preview.setEnabled(false);
			preview.setEnabled(false);
			okButton.setEnabled(false);
			okButton.setEnabled(false);

		}
	}

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, VAR.TAKE_PICTURE);
	}

	@Override
	protected void onRestart() {

		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isShowOkBt();
		gridImageAdapter.notifyDataSetChanged();
	}
}
